#include "UTHString.h"

namespace phnq
{
	namespace uth
	{
		UTHString::UTHString(const char* chars) : UTHValue(UTH_VALUE_TYPE_STRING)
		{
			this->chars = (char*)malloc(strlen(chars)+1);
			strcpy(this->chars, chars);
		}

		UTHString::~UTHString()
		{
			free(this->chars);
		}
	
		bool UTHString::equals(UTHValue *val)
		{
			if(val->isString())
			{
				UTHString *s = (UTHString*)val;
				return strcmp(s->getChars(), getChars()) == 0;
			}
			else
			{
				return false;
			}
		}
	
		int UTHString::hash()
		{
			char *str = chars;
		
	        unsigned long hash = 0;
	        int c;

	        while (c = *str++)
	            hash = c + (hash << 6) + (hash << 16) - hash;
		
			return (int)hash;
		}

		char* UTHString::getChars()
		{
			return this->chars;
		}

		void UTHString::serialize(stringbuf *sb)
		{
			sb->sputc('"');

			int len = strlen(chars);
			for(int i=0; i<len; i++)
			{
				char c = chars[i];
			
				switch(c)
				{
					case '\n':
						sb->sputc('\\');
						sb->sputc('n');
						break;
				
					case '\r':
						sb->sputc('\\');
						sb->sputc('r');
						break;
					
					case '\t':
						sb->sputc('\\');
						sb->sputc('t');
						break;

					case '"':
						sb->sputc('\\');
						sb->sputc('"');
						break;

					case '\\':
						sb->sputc('\\');
						sb->sputc('\\');
						break;
					
					default:
						sb->sputc(c);
				}
			}

			sb->sputc('"');
		}
	}
}
